package com.offcn.sellergood.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.entity.Cart;
import com.offcn.pojo.OrderItem;
import com.offcn.sellergood.dao.ItemMapper;
import com.offcn.sellergood.pojo.Item;
import com.offcn.sellergood.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/****
 * @Author:ujiuye
 * @Description:Item业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper,Item> implements ItemService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ItemMapper itemMapper;
    /**
     * @param: String status
     * @return: List<Item>
     * @description: 根据商品的状态获取item
     * @analyze:
     */
    @Override
    public List<Item> findByStatus(String status) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("status",status);
        return itemMapper.selectList(wrapper);
    }

    // 根据商品的id来获取商品的信息
    @Override
    public Item findById(Long itemId) {
        Item item = this.getById(itemId);
        return item;
    }

    @Override
    public void dearCount(String username) {
        // 根据用户名来获取购物车的数据
        String carts = (String) redisTemplate.boundHashOps("cartList").get(username);
        List<Cart> cartList = JSON.parseArray(carts, Cart.class);
        // 遍历每一个购物车中的每一个订单列表
        for (Cart cart : cartList) {
            for (OrderItem orderItem : cart.getOrderItemList()) {
                int rows = itemMapper.dearCount(orderItem);
                if (rows <= 0) {
                    throw new RuntimeException("库存不足，请及时添加商品");
                }
            }
        }
    }
}
